package com.richard.base.net.interceptors

import com.richard.base.net.utils.DomainUrlParser
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response


class ChangeBaseUrlInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        //获取request
        val request = chain.request()

        //从request中获取原有的HttpUrl实列 oldHttpUrl

        val oldHttpUrl = request.url

        //获取request的创建者
        val builder = request.newBuilder()

        //如果有忽略
        var urlString = oldHttpUrl.toString()
        if (urlString.contains(GlobalUrlManager.IDENTIFICATION_IGNORE)) {
            return chain.proceed(pruneIdentification(builder, urlString))
        }

        val headerValues = request.headers(GlobalUrlManager.DOMAIN)

        if (headerValues.isNotEmpty()) {
            builder.removeHeader(GlobalUrlManager.DOMAIN)
            //单个接口替换
            val newBaseUrl: HttpUrl? = GlobalUrlManager.instance.mDomain[headerValues[0]]?.toHttpUrlOrNull()

            newBaseUrl?.run {
                val newHttpUrl =
                    oldHttpUrl.newBuilder().scheme(scheme).host(host)
                        .port(port).build()
                return chain.proceed(builder.url(newHttpUrl).build())
            }
        } else {
            //全局替换
            var httpUrl = GlobalUrlManager.instance.globalDomain
            if (null != httpUrl) {
                val urlParser = DomainUrlParser()
                val newUrl: HttpUrl = urlParser.parseUrl(httpUrl, request.url)

                return chain.proceed(builder.url(newUrl).build())
            }
        }
        return chain.proceed(request)
    }

    private fun pruneIdentification(newBuilder: Request.Builder, url: String): Request {
        var split = url.split(GlobalUrlManager.IDENTIFICATION_IGNORE)
        var buffer = StringBuffer()
        for (s in split) {
            buffer.append(s)
        }
        return newBuilder
            .url(buffer.toString())
            .build()
    }


}